#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <gtk/gtk.h>

#include "callbacks.h"
#include "interface.h"
#include "support.h"
#include "debug.h"
#include "about.h"
#include "help.h"
#include "message.h"
#include <string.h> 
#include <unistd.h>
#include <mysql.h>
#include <stdlib.h>
int BUTTON_RIGHT =  0x3;
extern MYSQL *conn;
extern struct info_struct reader_info;
extern struct borrow_struct borrow_info;

void time_borrow(char *time_old)
{
	int yeah,month,day;
	char *temp;
	
	temp = strrchr(time_old, '-');
	day = atoi(temp+1);
	*temp = '\0';
	
	temp = strchr(time_old, '-');
	month = atoi(temp+1);
	*temp = '\0';
	
	yeah = atoi(time_old);
		
	debug_print("test time2:%d %d %d\n", yeah, month, day);
	if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 ) && (day >24)) {
	  	month++;
	  	day=day+7;
	  	day-=31;
	} else if(month == 12 && day>24) {
		month=1;
		yeah++;
		day=day+7;
		day-=31;
	} else if((month == 4 || month == 6 || month == 9 || month == 11 ) && (day>23)) {
		month++;
		day=day+7;
		day=day-30;
	} else if(month==2 && day>21) {
		month++;
		day=day+7;
		day=day-28;
	} else day=day+7;
	memset(time_old, '\0', strlen(time_old));
	snprintf(time_old, 12, "%d-%d-%d", yeah, month, day);
	debug_print("test 3:%s\n", time_old);
	return ;
}
void
on_menu_quit_activate                  (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	debug_where();
	gtk_main_quit();
}


void
on_login_activate                      (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	GtkWidget *window_login =  create_window_login ();
	gtk_widget_show(window_login);
	debug_where();
}


void
on_info_activate                       (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	//struct info_struct *reader_info = (struct info_struct *)user_data;
	char selectinfo[128];
	MYSQL_RES *res;
	MYSQL_ROW row;
	GtkWidget *window_info = create_window_info();
	
	debug_print("test: %s\n", rnumber);
	sprintf(selectinfo, "select * from reader where number='%s'", rnumber);
	debug_print("test2:%s\n", selectinfo);
	if (mysql_query(conn, selectinfo)) {
		show_message(reader_info.window_info, GTK_MESSAGE_ERROR, "系统错误：读取该读者信息出现错误");
		return ;
	}
	
	debug_print("here?\n");
	res = mysql_store_result(conn);
	debug_print("i am here\n");
	while ((row = mysql_fetch_row(res)) != NULL) {
		debug_print("%s:%s:%s:%s:%s \n", row[0], row[1], row[2], row[3], row[4]);
		gtk_entry_set_text(GTK_ENTRY(reader_info.entry_rnumber), row[0]);
		gtk_entry_set_text(GTK_ENTRY(reader_info.entry_rname), row[1]);
		gtk_entry_set_text(GTK_ENTRY(reader_info.entry_sex), row[2]);
		gtk_entry_set_text(GTK_ENTRY(reader_info.entry_department), row[3]);
		gtk_entry_set_text(GTK_ENTRY(reader_info.entry_phone), row[4]);
	}
	debug_where();
	gtk_widget_show(window_info);
}


void
on_borrow_activate                     (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	GtkWidget *window_borrow = create_window_borrow();
	//struct borrow_struct *borrow_info = (struct borrow_struct *)user_data;
	char select_sql[128];
	char *clist_res[3];
	int i;
	MYSQL_ROW row;
	MYSQL_RES *res;
	gtk_clist_clear(GTK_CLIST(borrow_info.clist_borrow));
	sprintf(select_sql, "select bname, borrow.bnumber,reback from borrow,book where borrow.bnumber=book.bnumber and rnumber='%s'", rnumber);
	if (mysql_query(conn, select_sql)) {
		show_message(window_borrow, GTK_MESSAGE_ERROR, "系统错误：查找借阅信息错误");
		return ;
	}
	res = mysql_store_result(conn);
	while((row = mysql_fetch_row(res)) != NULL) {
		for(i=0; i<3; i++) clist_res[i] = row[i];
		gtk_clist_append(GTK_CLIST(borrow_info.clist_borrow), clist_res);
	}
	gtk_widget_show(window_borrow);
	debug_print("find from mysql\nshow info\n");
}


void
on_change_activate                     (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	GtkWidget *window_change = create_window_change();
	gtk_widget_show(window_change);
	debug_where();
}


void
on_logout_activate                     (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	GtkWidget *menu_read = (GtkWidget *)user_data;
	gtk_widget_set_sensitive(menu_read, FALSE);
	memset(rnumber, '\0', strlen(rnumber));
	debug_where();
}


void
on_topic_activate                      (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	GtkWidget *window_help = create_window_help();
	gtk_widget_show(window_help);
	debug_where();
}


void
on_about_activate                      (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	GtkWidget *window_about = create_window_about();
	gtk_widget_show(window_about);
	debug_where();
}


void
on_button_find_clicked                 (GtkButton       *button,
                                        gpointer         user_data)
{
	struct book_find_struct *book_find = (struct book_find_struct *)user_data;
	const gchar *type, *model, *word;
	char find_sql[128];
	MYSQL_RES *res;
	MYSQL_ROW row;
	char *clist_row[9];
	int count = 9;
	int flag=0;

	type = (const gchar *)gtk_entry_get_text(GTK_ENTRY(GTK_BIN(book_find->comb_type)->child));
	model = (const gchar *)gtk_entry_get_text(GTK_ENTRY(GTK_BIN(book_find->com_model)->child));
	word = (const gchar *)gtk_entry_get_text(GTK_ENTRY(book_find->entry_word));
	gtk_clist_clear(GTK_CLIST(book_find->clist_result));

	if (!strlen(type) || !strlen(model) || !strlen(word)) {
		char message[] = "各项数据不能为空";
		show_message(book_find->window_main, GTK_MESSAGE_INFO, message);
		return ;
	}
	
	if (!strcmp(type, "作者") && !strcmp(model, "精确")) {
		sprintf(find_sql, "select * from book where author='%s'",word);
	} else if (!strcmp(type, "作者") && !strcmp(model, "模糊")) {
		strcpy(find_sql, "select * from book where author like '%");
		strcat(find_sql,word);
		strcat(find_sql,"%'");
	} else if (!strcmp(type, "书刊名称") && !strcmp(model, "精确")) {
		sprintf(find_sql, "select * from book where bname='%s'",word);
	} else if (!strcmp(type, "书刊名称") && !strcmp(model, "模糊")) {
		strcpy(find_sql, "select * from book where bname like '%");
		strcat(find_sql, word);
		strcat(find_sql,"%'");
	} 
	debug_print("%s\n", find_sql);
	if (mysql_query(conn, find_sql)) {
		show_message(book_find->window_main, GTK_MESSAGE_ERROR, "系统错误：修改密码出现错误");
		return ;
	}
	res = mysql_store_result(conn);
	while ((row = mysql_fetch_row(res)) != NULL) {
		debug_print("%s:%s:%s:%s:%s \n", row[0], row[1], row[2], row[3], row[4]);
		for(count = 0;count < 9; count ++) clist_row[count] = row[count];
		gtk_clist_append(GTK_CLIST(book_find->clist_result), clist_row);
		flag = 1;
	}
	if (flag == 0) show_message(book_find->window_main, GTK_MESSAGE_INFO, "没有找到");
	debug_where();
	debug_print("test:%s,%s,%s\n",word, type, model);
}


void
on_button_login_clicked                (GtkButton       *button,
                                        gpointer         user_data)
{
	
	struct login_struct *login = (struct login_struct *)user_data;
	MYSQL_RES *res;
	const gchar *rnum,*password;
	char login_sql[512];
	rnum = (const gchar *)gtk_entry_get_text(GTK_ENTRY
						(login->entry_rnumber));
	password = (const gchar *)gtk_entry_get_text(GTK_ENTRY
					(login->entry_password));
	debug_print("test:%s,%s\n", rnum, password);
	/*  在数据库中查询，验证，如果错误，处理结果 */
	//验证成功
	if (!strlen(rnum) || !strlen(password) || strlen(rnum) > 20 || strlen(password) > 15) {
		char message[] = "证件号码和密码不能为空！\n且证件号码要小于20,密码要小于15";
		show_message(login->window_login, GTK_MESSAGE_ERROR, message);
		return ;
	}
	sprintf(login_sql,"select * from reader where number = '%s' and password = '%s'", rnum, password);
	debug_print("sql:%s\n", login_sql);
	mysql_query(conn, login_sql);
	res = mysql_store_result(conn);
	debug_where();
	if (!mysql_num_rows(res)) {
		show_message(login->window_login, GTK_MESSAGE_INFO, "无此读者，请确认密码和证件号码");
		debug_where();
		return ;
	}
	strcpy(rnumber, rnum);
	strcpy(rpassword, password);
	debug_print("全局变量：rnumber:%s\n", rnumber);
	gtk_widget_destroy(login->window_login);
	gtk_widget_set_sensitive(login->menu, TRUE);
}

void on_button_login_cancel_clicked(GtkButton *button, gpointer user_data)
{
	GtkWidget *window_login = (GtkWidget *)user_data;
	memset(rnumber, '\0', strlen(rnumber));
	debug_where();	
	gtk_widget_destroy(window_login);
}


gboolean
on_clist_borrow_button_press_event     (GtkWidget       *widget,
                                        GdkEventButton  *event,
                                        gpointer         user_data)
{
	GtkWidget *right_menu;
	debug_where();
	if (event->button == BUTTON_RIGHT) {
		right_menu = create_menu_pop();
		gtk_menu_popup(GTK_MENU(right_menu), NULL, NULL, NULL, NULL, event->button, event->time);
		return TRUE;
	}
	return FALSE;
}


void
on_button_change_ok_clicked            (GtkButton       *button,
                                        gpointer         user_data)
{
	struct change_struct *change_info = (struct change_struct *)user_data;
	const gchar *password_old;
	const gchar *password_one;
	const gchar *password_two; 
	char change_sql[128];
	
	debug_print("得到各个密码，修改");
	password_old = gtk_entry_get_text(GTK_ENTRY(change_info->entry_password));
	password_one = gtk_entry_get_text(GTK_ENTRY(change_info->entry_new_p));
	password_two = gtk_entry_get_text(GTK_ENTRY(change_info->entry_new_p_a));
	
	if (!strlen(password_old) || !strlen(password_one) || 
	    !strlen(password_two) || strlen(password_old) > 15 || 
	    strlen(password_one) > 15 || strlen(password_two) > 15) {
	    	char message[] = "密码长度大于0小于15";
	    	show_message(change_info->window_change, GTK_MESSAGE_INFO, message);
		return ;
	 }
	if (strcmp(password_one, password_two) != 0) {
		char message[] = "新密码与确认密码不同";
	    	show_message(change_info->window_change, GTK_MESSAGE_INFO, message);
		return ;
	}
	if (strcmp(password_old, rpassword) != 0) {
		char message[] = "原始密码错误";
	    	show_message(change_info->window_change, GTK_MESSAGE_INFO, message);
		return ;
	}
	
	sprintf(change_sql, "update reader set password='%s' where number='%s'", password_one, rnumber);
	if (mysql_query(conn, change_sql)) {
		show_message(change_info->window_change, GTK_MESSAGE_ERROR, "系统错误：修改密码出现错误");
		return ;
	}
	strcpy(rpassword, password_one);
	
	show_message(change_info->window_change, GTK_MESSAGE_INFO, "修改密码成功");
	gtk_widget_destroy(change_info->window_change);
}


void
on_button_change_cancel_clicked        (GtkButton       *button,
                                        gpointer         user_data)
{
	debug_where();
	gtk_widget_destroy(GTK_WIDGET(user_data));
}


void
on_borrow_again_activate               (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	debug_where();
	char time_old[14], *time;
	char bnumber[20], *b;
	int flag = 0;
	char update_sql[150];
	char select_sql[150];
	MYSQL_ROW row;
	MYSQL_RES *res;

	gtk_clist_get_text(GTK_CLIST(borrow_info.clist_borrow),borrow_info.clist_row,2,(char **)&time);
	gtk_clist_get_text(GTK_CLIST(borrow_info.clist_borrow),borrow_info.clist_row,1,(char **)&b);
	strcpy(time_old,time);
	strcpy(bnumber,b);
	
	snprintf(select_sql, 150, "select flag from borrow where bnumber = '%s' and rnumber = '%s'", bnumber, rnumber);
	if (mysql_query(conn, select_sql)) {
		show_message(borrow_info.window_main, GTK_MESSAGE_ERROR, "系统错误：读取数据错误");
		return ;
	}
	res = mysql_store_result(conn);
	if ((row = mysql_fetch_row(res)) != NULL) {
		flag = atoi(&row[0][0]);
	}
	if (flag == 1) {
		show_message(borrow_info.window_main, GTK_MESSAGE_INFO, "sorry~只能续借一次");
		return ;
	}
	debug_print("test:%s,%s,%d\n", time_old, bnumber, flag);
	time_borrow(time_old);
	debug_print("new time:%s\n", time_old);
	
	snprintf(update_sql, 150, "update borrow set reback='%s',flag = 1 where bnumber ='%s' and rnumber='%s'",
				time_old, bnumber, rnumber);
	debug_print("sql:%s\n", update_sql);
	if(mysql_query(conn, update_sql)) {
		show_message(borrow_info.window_main, GTK_MESSAGE_ERROR, "系统错误：更新借阅数据错误");
		return ;
	}
	gtk_clist_set_text(GTK_CLIST(borrow_info.clist_borrow),borrow_info.clist_row,2, time_old);
	return ;
}
void
on_select_row                          (GtkCList        *clist,
                                        gint             row,
                                        gint             column,
                                        GdkEvent        *event,
                                        gpointer         user_data)
{
	borrow_info.clist_row = row;
}

